package me.goldze.mvvmhabit.net;

import android.text.TextUtils;
import android.util.Log;

import com.hjq.toast.ToastUtils;

import java.io.IOException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.goldze.mvvmhabit.utils.GsonUtils;
import retrofit2.adapter.rxjava2.HttpException;


/**
 * LkSSubscriber
 */
public abstract class LkSSubscriberNew<T> implements Observer<T> {

    public LkSSubscriberNew() {
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(T t) {
        LKSResponseNew lksResponse = null;

        try {
            lksResponse = (LKSResponseNew) t;
        } catch (Exception e) {
            if (null == lksResponse) {
                throw new IllegalArgumentException("传入的类型不匹配！请传入LKSResponse");
            }
        }
        try {
            if (lksResponse.getState() ==0) {
                Log.e("bruce", "onNext: >>>>>>>>>>>"+lksResponse.toString());
                onSuccess(lksResponse.getData());
            } else {
                onFail(lksResponse.getMessage());
            }
        }catch (Exception e){
            onError(e);
        }

    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        try{
            if (e instanceof ExceptionHandle.ResponeThrowable) {

                onError((ExceptionHandle.ResponeThrowable) e);
            } else if(e instanceof HttpException){
                try {
                    String string = ((HttpException) e).response().errorBody().string();
                    if(TextUtils.isEmpty(string)){
                        onFail("网络错误");
                        return;
                    }
                    String message = GsonUtils.getValueByName(string, "message");
                    int code = GsonUtils.getIntValue(string, "code");
                    onFail(code);
                    onFail(message);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
                onError(new ExceptionHandle.ResponeThrowable(e, ExceptionHandle.ERROR.UNKNOWN));
            }else {
                onError(new ExceptionHandle.ResponeThrowable(e, ExceptionHandle.ERROR.UNKNOWN));
                ToastUtils.show("网络链接错误！");
            }
        }catch (Exception ex){

        }

    }


    @Override
    public void onComplete() {

    }
    public void onTokenFail() {

    }
    public void onFail(int errCode) {

    }

    /**
     * 连接错误
     *
     * @param e
     */
    public abstract void onError(ExceptionHandle.ResponeThrowable e);

    /**
     * 服务器错误
     *
     * @param s
     */
    public abstract void onFail(String s);

    /**
     * 成功
     *
     * @param result
     */
    public abstract void onSuccess(Object result);

}
